﻿using app.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;

namespace app
{
	public class GSXTHelper
    {
        private static string url = null;
        private static string apicode = null;

        public static void UpdateConfig()
        {
            GSXT gsxt = GSXT.GetEnabled();

            if(gsxt == null)
            {
                throw new Exception("未启用任何企业查询接口！");
            }

            url = gsxt.url;
            apicode = gsxt.apicode;
        }

        private static void InitConfig()
        {
            if(url == null)
            {
                UpdateConfig();
            }
        }

        public static GSInfo GetByFullName(string full_name)
        {
            string result = GetRequest(new Dictionary<string, string> {
                { "fullname", full_name }
            });

            GSCorpDetail detail = null;
            try
            {
                GSResultForFullNameQuery result_obj = Newtonsoft.Json.JsonConvert.DeserializeObject<GSResultForFullNameQuery>(result);
                if (result_obj.state == "200")
                {
                    detail = result_obj.details.First();
                }
            }
            catch(Exception e)
            {
                throw new Exception("企业查询返回数据解析错误:" + e.Message);
            }

            if(detail == null)
            {
                return null;
            }
            else
            {
                return detail.ToGSInfo();
            }
        }

        private static string GetRequest(Dictionary<string, string> the_params)
        {
            InitConfig();

            string params_str = GenerateParamsStr(the_params);
            string url_with_params = url + "?" + params_str;
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url_with_params);
            httpRequest.Timeout = 2000;
            httpRequest.Method = "GET";
            httpRequest.Headers.Add("authoration", "apicode");
            httpRequest.Headers.Add("apicode", apicode);
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();
            result = result.Replace("\r", "").Replace("\n", "").Replace("\t", "");
            int status = (int)httpResponse.StatusCode;
            sr.Close();

            if(status == 200)
            {
                return result;
            }
            else
            {
                throw new Exception("企业查询接口请求错误");
            }
        }

        private static string GenerateParamsStr(Dictionary<string, string> the_params)
        {
            string params_str = "";
            foreach (string key in the_params.Keys)
            {
                params_str += GenerateParamStr(key, the_params[key]);
            }
            return params_str;
        }

        private static string GenerateParamStr(string key, string value)
        {
            return key + "=" + value + "&";
        }
    }

    public class GSInfo
    {
        public string corpname { get; set; } // 公司名称
        public string address { get; set; } // 公司地址
        public string creditcode { get; set; } // 统一社会信用代码
        public string gongsh { get; set; } // 工商注册号
        public string orgcode { get; set; } // 组织机构代码
        public string state { get; set; } // 经营状态
        public string type { get; set; } // 公司类型
        public string regtime { get; set; } // 注册时间
        public string proxyer { get; set; } // 法人
        public double money { get; set; } // 注册资本
        public string onlinetime { get; set; } // 营业期限
        public string regpart { get; set; } // 注册机关
        public string fieldrange { get; set; } // 经营范围
        public string industry { get; set; } // 行业
        public string email { get; set; } // 邮箱
        public string phone { get; set; } // 联系电话
        public bool hasUnify { get; set; } // 是否三证合一
        public string shortcut { get; set; } // 公司简介
    }

    class GSResultForFullNameQuery
    {
        public string result { get; set; }
        public string state { get; set; }
        public int total { get; set; }
        public List<GSCorpDetail> details { get; set; }
    }

    class GSCorpDetail
    {
        public string corpname { get; set; } // 公司名称
        public string website { get; set; } // 公司官网
        public string address { get; set; } // 公司地址
        public string creditcode { get; set; } // 统一社会信用代码
        public string gongsh { get; set; } // 工商注册号
        public string orgcode { get; set; } // 组织机构代码
        public string state { get; set; } // 经营状态
        public string type { get; set; } // 公司类型
        public string regtime { get; set; } // 注册时间
        public string proxyer { get; set; } // 法人
        public string money { get; set; } // 注册资本
        public string onlinetime { get; set; } // 营业期限
        public string regpart { get; set; } // 注册机关
        public string fieldrange { get; set; } // 经营范围
        public string industry { get; set; } // 行业
        public string email { get; set; } // 邮箱
        public string phone { get; set; } // 联系电话
        public string taxNumber { get; set; } // 纳税人识别号
        public string hasUnify { get; set; } // 是否三证合一
        public string shortcut { get; set; } // 公司简介
        public List<GSPerson> persons { get; set; } // 人员
        public List<GSHolder> holders { get; set; } // 股东

        public GSInfo ToGSInfo()
        {
            GSInfo info = new GSInfo();
            info.corpname = this.corpname;
            info.address = this.address;
            info.creditcode = this.creditcode;
            info.gongsh = this.gongsh;
            info.state = this.state;
            info.type = this.type;
            info.regtime = this.regtime;
            info.proxyer = this.proxyer;

            string pattern = @"^\d+\.?\d?";
            string money_str = Regex.Match(this.money, pattern).Value;
            double temp_money = 0;
            if(double.TryParse(money_str, out temp_money))
            {
                info.money = temp_money;
            }

            info.onlinetime = this.onlinetime;
            info.regpart = this.regpart;
            info.fieldrange = this.fieldrange;
            info.industry = this.industry;
            info.email = this.email;
            info.phone = this.phone;
            info.hasUnify = this.hasUnify == "yes" ? true : false;
            info.shortcut = this.shortcut;
            return info;
        }
    }

    class GSPerson // 人员
    {
        public string name { get; set; } // 姓名
        public string position { get; set; } // 职务
    }

    class GSHolder // 股东
    {
        public string name { get; set; } // 姓名
        public string rate { get; set; } // 持股比例
        public string fund { get; set; } // 认缴出资额（万元）
        public string funddate { get; set; } // 出资日期
        public string type { get; set; } // 出资类型
    }
}